import nodemailer from 'nodemailer';

interface EmailOptions {
  to: string;
  subject: string;
  text: string;
  html: string;
}

/**
 * 发送电子邮件
 */
export async function sendEmail({ to, subject, text, html }: EmailOptions) {
  // 获取环境变量
  const {
    EMAIL_SERVER_HOST,
    EMAIL_SERVER_PORT,
    EMAIL_SERVER_USER,
    EMAIL_SERVER_PASSWORD,
    EMAIL_FROM,
    EMAIL_DOMAIN,
    EMAIL_FROM_NAME,
    TENCENT_CLOUD_SECRET_ID,
    TENCENT_CLOUD_SECRET_KEY
  } = process.env;

  // 检查是否有完整的SMTP配置
  const hasSmtpConfig = EMAIL_SERVER_HOST && EMAIL_SERVER_PORT && EMAIL_SERVER_USER && EMAIL_SERVER_PASSWORD && EMAIL_FROM;
  
  // 检查是否有腾讯云配置
  const hasTencentConfig = TENCENT_CLOUD_SECRET_ID && TENCENT_CLOUD_SECRET_KEY && EMAIL_FROM;

  // 如果没有邮件发送配置，使用控制台输出模式
  if (!hasSmtpConfig && !hasTencentConfig) {
    console.warn('邮件服务器配置不完整，使用控制台输出模式');
    console.log('-------------------------');
    console.log('发送邮件:');
    console.log(`收件人: ${to}`);
    console.log(`主题: ${subject}`);
    console.log(`内容: ${text}`);
    console.log('-------------------------');
    
    // 返回模拟的成功发送信息
    return {
      messageId: `console-mode-${Date.now()}`,
      envelope: {
        from: EMAIL_FROM || '5555@grym.asia',
        to: [to]
      }
    };
  }

  try {
    // 如果有SMTP配置，优先使用SMTP
    if (hasSmtpConfig) {
      // 创建邮件传输器
      const transporter = nodemailer.createTransport({
        host: EMAIL_SERVER_HOST,
        port: parseInt(EMAIL_SERVER_PORT),
        secure: parseInt(EMAIL_SERVER_PORT) === 465,
        auth: {
          user: EMAIL_SERVER_USER,
          pass: EMAIL_SERVER_PASSWORD,
        },
      });

      // 发送邮件
      const info = await transporter.sendMail({
        from: EMAIL_FROM_NAME ? `"${EMAIL_FROM_NAME}" <${EMAIL_FROM}>` : EMAIL_FROM,
        to,
        subject,
        text,
        html,
      });

      console.log(`邮件已发送: ${info.messageId}`);
      return info;
    }
    
    // 如果没有SMTP配置但有腾讯云配置，可以在这里添加腾讯云邮件发送逻辑
    // 由于需要额外的SDK，这里仍然使用控制台输出
    console.warn('没有完整的SMTP配置，但检测到腾讯云配置。请完善SMTP配置或集成腾讯云邮件SDK');
    console.log('-------------------------');
    console.log('发送邮件(腾讯云模式):');
    console.log(`收件人: ${to}`);
    console.log(`主题: ${subject}`);
    console.log(`内容: ${text}`);
    console.log('-------------------------');
    
    // 返回模拟的成功发送信息
    return {
      messageId: `tencent-cloud-mode-${Date.now()}`,
      envelope: {
        from: EMAIL_FROM || '5555@grym.asia',
        to: [to]
      }
    };
  } catch (error) {
    console.error('邮件发送失败:', error);
    throw error;
  }
} 